package com.dson.gateway.filter;

import com.dson.common.LagouResponse;
import com.dson.common.pojo.UserResult;
import com.dson.common.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    private static final String LG_U_TOKEN = "lg_u_token";

    @Reference
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String requestPath = request.getPath().value();
        System.out.println(requestPath);
        if (requestPath.startsWith("/api/user") || requestPath.startsWith("/api/code")) {
            return chain.filter(exchange);
        }
        String token = Optional.ofNullable(request.getCookies().getFirst(LG_U_TOKEN)).map(HttpCookie::getValue).orElse(null);
        if (StringUtils.isNotBlank(token)) {
            UserResult checkTokenResponse = userService.verifyToken(token);
            if (StringUtils.isNotEmpty(checkTokenResponse.getToken())) {
                String welcomeUrl = "http://localhost/welcome.html?email=" + checkTokenResponse.getEmail();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, welcomeUrl);
                return response.setComplete();
            }
            clearCookie(response, LG_U_TOKEN);
        }
        String loginUrl = "http://localhost/login.html";
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set(HttpHeaders.LOCATION, loginUrl);
        return response.setComplete();
    }

    private void clearCookie(ServerHttpResponse response, String name) {
        response.addCookie(ResponseCookie.from(name, "").domain("localhost").path("/").maxAge(0).build());
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
